import { login, getInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken() || null,
    userInfo: {}
  },
  mutations: {
    setToken(store, token) {
      store.token = token
      setToken(token)
    },
    delToken(store) {
      store.token = null
      removeToken()
    },
    setUserInfo(store, userInfo) {
      store.userInfo = userInfo
    },
    removeUserInfo(store) {
      store.userInfo = {}
    }
  },
  actions: {
    async loginReq(context, data) {
      const res = await login(data)
      // console.log(res)
      context.commit('setToken', res.data)
    },
    async getUserInfo(context) {
      const res = await getInfo()
      // console.log(res.data, 111)
      const userId = await getUserDetailById(res.data.userId)
      // console.log(userId, 222)
      context.commit('setUserInfo', { ...res.data, ...userId.data })
      // 当前用户可以看到的菜单 res.data.roles.menus
      return res.data.roles.menus
    },
    // 退出时
    logout(context) {
      // 1.删除token
      context.commit('delToken')
      // 2.清空个人信息
      context.commit('removeUserInfo')
      // 3. 重置路由
      resetRouter()
    }
  }
}
